<template>
  <div>
    <!-- 添加按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="margin:10px 0px" @click="showDialog">添加</el-button>
    <!-- 表格
          data:表格组件要展示的数据---数组类型
          ElementUI表格展示的数据是以列为单位展示
            type:
    -->
    <el-table style="width: 100%" border :data="list">
      <!-- 表格每一列
            label:显示的标题--字符串
            width：对应列的宽度
            align：对齐
            prop:对应列内容的字段名
      -->
      <el-table-column type="index" prop="prop" label="序号" width="80px" align="center">
      </el-table-column>
      <el-table-column prop="descript" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="prop" label="品牌logo" width="width">
        <!-- table组件会把数组中数据进行回传，可以进行接收
          row:每行数据
          $index:每行数据索引值
        -->
        <template slot-scope="{row,$index}">
          <img :src="row.logo" alt="" style="width:100px;height:100px">
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器
    :current-page：当前第几页
    :total：数据总条数
    :page-size：每页展示的条数
    :page-sizes：代表可以设置每页展示多少条数据
    layout：分页器布局
    :pager-count：可点击页的数量
    连续页码数
    点击某一页按钮 -->
    <el-pagination 
      style="margin-top:20px;text-align:center"
      :total="total" 
      :current-page="page" 
      :page-size="limit" 
      :page-sizes="[3,5,10]"
      :pager-count="5"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="prev,pager,next,jumper,->,sizes,total">
    </el-pagination>
    <!-- 对话框 
      :visible.sync:控制对话框显示或隐藏用的
      只需要通过 rules 属性传入约定的验证规则，并将 Form-Item 的 prop 属性设置为需校验的字段名即可
    -->
    <el-dialog :title="tmForm.brandId?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <!-- form表单 
        :model:把表单的数据收集到哪个对象的身上，将来表单验证也需要这个属性
      -->
      <el-form style="width:80%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="name">
          <el-input autocomplete="off" v-model="tmForm.name"></el-input>
        </el-form-item>
        <el-form-item label="品牌图标" label-width="100px" prop="logo">
          <!-- 图片上传
            这里收集数据不能使用v-model，因为不是表单元素
            action:设置图片上传的地址
            :on-success:当图片上传成功会执行一次
            :before-upload：上传图片之前会执行一次
           -->
          <!-- <el-upload
            class="avatar-uploader"
            action="/thirdparty/oss/policy"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"> -->
          <el-upload
            class="avatar-uploader"
            action="http://jin-mall.oss-cn-beijing.aliyuncs.com"
            :data="dataObj"
            list-type="picture"
            :multiple="false" 
            :show-file-list="showFileList"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :on-preview="handlePreview">
            <img v-if="tmForm.logo" :src="tmForm.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name: 'tradeMark',
    data() {
      // 自定义校验规则
      var validateTmName = (rule, value, callback) => {
        if(value.length<2 || value.length>10){
          callback(new Error("品牌名称需要2-10位"));
        }else {
          callback();
        }
      };
      return {
        page:1, //分页器第几页
        limit:3, //当前页数展示数据条数
        total:0, //数据总条数
        list:[], //列表展示的数据
        dialogFormVisible:false, //控制对话框显示或隐藏的属性
        // 收集品牌信息
        tmForm:{
          name:'',
          logo:''
        },
                 dataObj: {
           policy: '',
           signature: '',
           key: '',
           ossaccessKeyId: '',
           dir: '',
           host: ''
          // callback:'',
         },
        // 表单验证的规则
        // require:必填 
        // message：提示 
        // trigger：用户行为设置（事件设置） blur失去焦点 change文本改变
        rules:{
          name: [
            { required: true, message: '请输入品牌名称', trigger: 'blur' },
            { validator: validateTmName, trigger: 'change' },
            // { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
          ],
          logo: [
            { required: true, message: '请选择品牌标识' }
          ],
        }
      }
    },
    mounted() {
      this.getPageList();
    },
    methods: {
      // 获取品牌列表
      async getPageList(pager=1){
        this.page = pager;
        // 解构出参数
        const {page,limit} = this;
        // 获取品牌列表接口
        let result = await this.$API.tradeMark.reqTradeMarkList(page,limit,'');
        if(result.code==200){
          console.log(result);
          this.total = result.data.totalCount;
          this.list = result.data.list;
        }
      },
      // 当前页改变被触发
      // pager:选中的页码会被回传
      handleCurrentChange(pager){
        this.getPageList(pager);
      },
      // page-size页展示条数发生变化时被触发
      // limit:选中条数会被回传
      handleSizeChange(limit){
        this.limit = limit;
        this.getPageList();
      },
      // 点击添加品牌按钮，显示对话框
      showDialog(){
        this.dialogFormVisible = true;
        this.tmForm = {name:'',logo:''};
      },
      // 修改某一品牌
      updateTradeMark(row){
        this.dialogFormVisible = true;
        // 将已有的品牌信息赋值给tmForm进行展示
        this.tmForm = {...row};
      },
      // 图片上传成功
      // res:上传成功后返回给前端的数据
      // file:上传成功后返回给前端的数据
      handleAvatarSuccess(res, file) {
        this.tmForm.logo = res.data; 
      },
      // 图片上传之前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      // 添加或修改品牌
      async addOrUpdateTradeMark(){
        this.$refs.ruleForm.validate(async (success)=>{
          if(success){
            this.dialogFormVisible = false;
            // 发请求
            let res = this.$API.tradeMark.reqAddOrUpdateTradeMark(this.tmForm);
            if(res.code==200){
              // 弹出信息提示
              this.$message.success(this.tmForm.brandId?'修改品牌成功':'添加品牌成功');
              // 如果修改品牌应该留在当前页
              this.getPageList(this.tmForm.brandId?this.page:1);
            }
          }else{
            console.log('error submit!!');
            return false;
          }
        })
      },
      // 删除品牌操作
      deleteTradeMark(row){
        // 弹框
        this.$confirm(`此操作将永久删除${row.name}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          // 发出请求
          let result = await this.$API.tradeMark.reqDeleteTradeMark(row.id);
          if(result.code==200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            // 再次获取品牌列表数据,当前页有数据则留在当前页，如果没有到上一页
            this.getPageList(this.list.length>1?this.page:this.page-1);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
             emitInput (val) {
         this.$emit('input', val)
       },
       handleRemove (file, fileList) {
         this.emitInput('')
       },
       handlePreview (file) {
         this.dialogVisible = true
       },
       beforeUpload (file) {
         let _self = this
         return new Promise((resolve, reject) => {
           policy().then(response => {
             _self.dataObj.policy = response.data.policy
             _self.dataObj.signature = response.data.signature
             _self.dataObj.ossaccessKeyId = response.data.accessid
             // eslint-disable-next-line no-template-curly-in-string
             _self.dataObj.key = response.data.dir + getUUID() + '_${filename}'
             _self.dataObj.dir = response.data.dir
             _self.dataObj.host = response.data.host
             resolve(true)
             // eslint-disable-next-line handle-callback-err
           }).catch(err => {
             // eslint-disable-next-line prefer-promise-reject-errors
             reject(false)
           })
         })
       },
       handleUploadSuccess (res, file) {
         console.log('上传成功...')
         this.showFileList = true
         this.fileList.pop()
         // eslint-disable-next-line standard/object-curly-even-spacing,no-template-curly-in-string
         this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name) })
         this.emitInput(this.fileList[0].url)
       }
    },
         computed: {
       imageUrl () {
         return this.value
       },
       imageName () {
         if (this.value != null && this.value !== '') {
           return this.value.substr(this.value.lastIndexOf('/') + 1)
         } else {
           return null
         }
       },
       fileList () {
         return [{
           name: this.imageName,
           url: this.imageUrl
         }]
       },
       showFileList: {
         get: function () {
           return this.value !== null && this.value !== '' && this.value !== undefined
         },
         set: function (newValue) {
         }
       }
     },
    
}
</script>

<style>
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>